<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>部门管理</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../admin/css/reset.css"/>
    <link rel="stylesheet" href="../../../admin/css/other/department.css"/>

</head>
<body class="pear-container">

<!-- 顶部查询表单 -->
<div class="layui-card">
    <div class="layui-card-body">

        <form class="top-search-from layui-form" action="">
            <div class="layui-form-item layui-inline">
                <label class="layui-form-label">代码</label>
                <div class="layui-input-inline">
                    <input type="text" name="code" placeholder="" class="layui-input layui-input-sm" autocapitalize="off">
                </div>
            </div>
            <div class="layui-form-item layui-inline">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" placeholder="" class="layui-input layui-input-sm" autocapitalize="off">
                </div>
            </div>

            <!--按钮部分-->
            <div class="layui-form-item layui-inline">
                <label class="layui-form-label"></label>
                <button class="pear-btn pear-btn-sm pear-btn-primary" lay-submit lay-filter="table-query">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button type="reset" class="pear-btn pear-btn-sm" lay-submit lay-filter="table-reset" permission="setting/user/insert">
                    <i class="layui-icon layui-icon-refresh"></i>重置
                </button>
                <!--收缩按钮-->
                <div class="layui-inline toggle-btn" style="margin-left: 5px;">
                    <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                    <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                </div>
            </div>
        </form>
    </div>
</div>

<!--数据表格-->
<div class="layui-row layui-col-space15">
    <div class="layui-col-md3">
        <div class="layui-card">
            <div class="layui-card-body">
                <div id="organizationTreeContent" style="overflow: auto">
                    <ul id="organizationTree" class="dtree organizationTree" data-id="9527"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md9">
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="table-data" lay-filter="table-data"></table>
                <div id="data-laypage"></div>
            </div>
        </div>
    </div>
</div>

<!--数据表头按钮-->
<script type="text/html" id="table-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="batchRemove">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
</script>


<!--操作按钮-->
<script type="text/html" id="table-bar">
    <button class="pear-btn pear-btn-primary pear-btn-xs layui-btn-sm" lay-event="edit">
        <i class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-xs layui-btn-sm" lay-event="remove">
        <i class="layui-icon layui-icon-delete"></i>
    </button>
</script>

<!--创建时间-->
<script type="text/html" id="data-createTime">
    {{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}
</script>

<!--更新时间-->
<script type="text/html" id="data-updateTime">
    {{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd')}}
</script>

<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script src="../../../lms/base64.js"></script>
<script src="../../../lms/common.js"></script>
<script src="../../../lms/permission.js"></script>
<script>

    const PRIMARY_KEY = "id";
    const SELECT_API = lms_config.api_url + "/api/setting/position/select";
    const UPDATE_API = lms_config.api_url + "/api/setting/position/update";
    const DELETE_API = lms_config.api_url + "/api/setting/position/delete";
    const SELECT_DEPT_API = lms_config.api_url + "/api/setting/dept/select";


    layui.use(['table', 'form', 'jquery', 'dtree', 'laypage', 'common'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let dtree = layui.dtree;
        let common = layui.common;
        let MODULE_PATH = "";
        let DTree;

        let cols = [
            [{
                type: 'checkbox'
            },
                {
                    title: '岗位代码',
                    field: 'position_code',
                    align: 'center'
                },
                {
                    title: '岗位名称',
                    field: 'position_name',
                    align: 'center'
                },
                {
                    title: '创建时间',
                    field: 'create_time',
                    align: 'center',
                    templet: '#data-createTime'
                },
                {
                    title: '更新时间',
                    field: 'update_time',
                    align: 'center',
                    templet: '#data-updateTime'
                },
                {
                    title: '操作',
                    toolbar: '#table-bar',
                    align: 'center',
                    width: 130
                }
            ]
        ]


        $request({
            url: SELECT_DEPT_API,
            type: 'GET',
            dataType: 'json',
        }).then(function (ret) {
            let data = buildTree(ret.data);
            DTree = dtree.render({
                elem: "#organizationTree",
                data: data,
                initLevel: "2", //默认展开层级为1
                line: true, // 有线树
                ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
                icon: ["0", "2"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
                method: 'get',
                headers: {Authorization: getUserInfo()["token"]},
            });
        }).catch(function (ret) {
            alert("出错" + ret.status + "：" + ret.responseText);
        });

        window.render = function (param) {
            let loading = layer.load();
            let where = (param === undefined) ? {} : param;
            if (where.page === undefined) {
                where.page = 1;
            }
            if (where.limit === undefined) {
                where.limit = 10;
            }

            $request({
                url: SELECT_API,
                type: 'GET',
                data: where,
                dataType: 'json',
            }).then(function (ret) {
                layer.close(loading);
                //重构多维数组变二维符合table渲染
                for (let item in ret.data) {
                    ret.data[item].userId = ret.data[item].id;
                    ret.data[item].username = ret.data[item].account;
                    ret.data[item].realName = ret.data[item].real_name;
                }

                table.render({
                    elem: '#table-data',
                    page: false,
                    cols: cols,
                    skin: 'line',
                    size: 'sm',
                    toolbar: '#table-toolbar',
                    defaultToolbar: [{
                        title: '刷新',
                        layEvent: 'refresh',
                        icon: 'layui-icon-refresh',
                    }, 'filter', 'print', 'exports'],
                    data: ret.data,
                });

                //分页处理
                layui.laypage.render({
                    elem: 'data-laypage',
                    count: ret.count,
                    curr: where.page,
                    limit: where.limit,
                    size: 'xs',
                    prev: '<i class="layui-icon layui-icon-left"></i>', // 自定义上一页按钮符号
                    next: '<i class="layui-icon layui-icon-right"></i>', // 自定义下一页按钮符号
                    limits: [10, 20, 40, 60, 80, 100, 300, 500],
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'], // 功能布局
                    jump: function (obj, first) {
                        if (!first) {
                            where.page = obj.curr;
                            where.limit = obj.limit;
                            // 分页切换时重新加载数据
                            window.render(where);
                        }
                    }
                });
            }).catch(function (ret) {
                layer.close(loading);
                layer.msg("出错[" + ret.status + "]：" + ret.responseText, {
                    icon: 2,
                    time: 1000
                });
            });
        }

        // 头部搜索栏
        form.on('submit(table-query)', function (data) {
            let param = data.field;
            param.page = 1
            window.render(param);
            return false;
        });

        // 绑定节点点击事件
        dtree.on("node(organizationTree)", function (obj) {
            if (!obj.param.leaf) {
                let $div = obj.dom;
                DTree.clickSpread($div); //调用内置函数展开节点
            } else {
                let param = {};
                param.department_id = obj.param.nodeId;
                param.page = 1
                window.render(param);
            }
        });

        table.on('tool(table-data)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            }
        });

        table.on('toolbar(table-data)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                window.refresh();
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });

        form.on('submit(organization-query)', function (data) {
            table.reload('table-data', {
                where: data.field
            })
            return false;
        });

        window.add = function () {
            layer.open({
                type: 2,
                title: '新增',
                shade: 0.1,
                area: [common.isModile() ? '100%' : '500px', common.isModile() ? '100%' : '400px'],
                content: MODULE_PATH + 'add.html?operation=add'
            });
        }

        window.edit = function (obj) {
            layer.open({
                type: 2,
                title: '修改',
                shade: 0.1,
                area: [common.isModile() ? '100%' : '500px', common.isModile() ? '100%' : '400px'],
                content: MODULE_PATH + 'add.html?operation=edit&id=' + obj.data.id
            });
        }

        window.remove = function (obj) {
            layer.confirm('确定要删除该权限', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    type: 'POST',
                    headers: {Authorization: getUserInfo()["token"]},
                    data: {"data": obj.data['id']},
                    dataType: 'json',
                    success: function (ret) {
                        layer.close(loading);
                        if (ret && ret.code == 0) {
                            layer.msg(ret.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                obj.del();
                            });
                        } else {
                            layer.msg(ret.msg, {
                                icon: 2,
                                //icon: 5,
                                time: 1000
                            });
                        }
                    },
                    error: function (ret) {
                        alert("出错" + ret.status + "：" + ret.responseText);
                    }, //表示如果请求响应出现错误，会执行的回调函数
                });
            });
        }

        window.batchRemove = function (obj) {

            //方法1：直接获得所有选择的ID
            let checkIds = common.checkField(obj, 'id');
            if (checkIds === "") {
                layer.msg("未选中数据", {
                    icon: 3,
                    time: 1000
                });
                return false;
            }

            layer.confirm('确定要删除这些权限', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    type: 'POST',
                    headers: {Authorization: getUserInfo()["token"]},
                    data: {"data": checkIds},
                    dataType: 'json',

                    success: function (ret) {
                        layer.close(loading);
                        if (ret && ret.code == 0) {
                            layer.msg(ret.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                window.render();
                            });
                        } else {
                            layer.msg(ret.msg, {
                                icon: 2,
                                time: 1000
                            });
                        }
                    },
                    error: function (ret) {
                        alert("出错" + ret.status + "：" + ret.responseText);
                    }, //表示如果请求响应出现错误，会执行的回调函数
                });
            });
        }

        // 构建树形结构数据左侧
        function buildTree(data, parentId = 0) {
            var tree = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i].pid === parentId) {
                    var node = {
                        id: data[i].id,
                        parentId: parentId,
                        title: data[i].department_name,
                        children: buildTree(data, data[i].id) // 递归构建子节点
                    };
                    tree.push(node);
                }
            }
            return tree;
        }

        window.render();

        window.refresh = function (param) {
            window.render();
        }
    })
</script>
</body>
</html>
